package com.ailanyin.admin.controller;

import com.ailanyin.admin.service.SysConfigService;
import com.ailanyin.common.result.AjaxResult;
import com.ailanyin.common.result.CommonPage;
import com.ailanyin.model.SysConfig;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@RestController
@RequestMapping("/system/config")
@Api(tags = "后台参数管理")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:config:list')")
    @ApiOperation(value = "获取参数配置列表")
    public CommonPage list(SysConfig config,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysConfig> list = sysConfigService.selectConfigList(config);
        return CommonPage.restPage(list);
    }


    @PreAuthorize("hasAuthority('system:config:query')")
    @GetMapping(value = "/{configId}")
    @ApiOperation(value = "根据参数编号获取详细信息")
    public AjaxResult getInfo(@PathVariable Long configId) {
        return AjaxResult.success(sysConfigService.selectConfigById(configId));
    }


    @PreAuthorize("hasAuthority('system:config:add')")
    @PostMapping
    @ApiOperation(value = "新增参数配置")
    public AjaxResult addSysConfig(@Validated @RequestBody SysConfig config) {
        sysConfigService.addSysConfig(config);
        return AjaxResult.success();
    }

    @PreAuthorize("hasAuthority('system:config:edit')")
    @PutMapping
    @ApiOperation(value = "修改参数配置")
    public AjaxResult updateSysConfig(@Validated @RequestBody SysConfig config) {
        sysConfigService.updateSysConfig(config);
        return AjaxResult.success();
    }


    @PreAuthorize("hasAuthority('system:config:remove')")
    @DeleteMapping("/{configIds}")
    @ApiOperation(value = "删除参数配置")
    public AjaxResult removeSysConfig(@PathVariable Long[] configIds) {
        sysConfigService.deleteConfigByIds(configIds);
        return AjaxResult.success();
    }

    @GetMapping(value = "/configKey/{configKey}")
    @ApiOperation(value = "根据参数键名查询参数值")
    public AjaxResult getConfigKey(@PathVariable String configKey) {
        return AjaxResult.success(sysConfigService.selectConfigByKey(configKey));
    }

}
